//
//  ANWebService+manage.m
//  Ants
//
//  Created by ZHM on 16/7/4.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANWebService+manage.h"

@implementation ANWebService (manage)

- (void)addCategory:(NSString *)categoryName completion:(void(^)(ANBDProductCategory *productCategory,BOOL succeeded, NSError *error))completion {
    BmobObject *obj = [BmobObject objectWithClassName:@"ProductCategory"];
    [obj setObject:categoryName forKey:@"title"];
    [obj setObject:[NSNumber numberWithBool:YES] forKey:@"isOnSales"];
    [obj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        //进行操作
        if (isSuccessful) {
            ANLog(@"-------------已经更新");
        }
        if (!error) {
            ANBDProductCategory *productCategory = [ANBDProductCategory MR_findFirstOrCreateByAttribute:@"title" withValue:categoryName inContext:self.sharedContext];
            productCategory.iconUrlString = [obj objectForKey:@"iconUrlString"];
            productCategory.title = categoryName;
            productCategory.bmObject = obj;
            [self.sharedContext MR_saveToPersistentStoreAndWait];
            ANLog(@"修改成功啦");
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,productCategory,YES,nil);
        } else {
            ANLog(@"修改失败啦");
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,nil,NO, error);
        }
    }];
}
- (void)deleProductCategoryWithObjectId:(NSString *)objectId completion:(void(^)(BOOL succeeded, NSError *error))completion {
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"ProductCategory"];
    [bquery getObjectInBackgroundWithId:objectId block:^(BmobObject *object, NSError *error) {
        if (!error) {
            if (object) {
                
                NSString *title = [object objectForKey:@"title"];
                ANLog(@"正在删除:%@",title);
                //删除服务器上
                [object deleteInBackground];
                //删除本地
                ANBDProductCategory *productCategory = [ANBDProductCategory MR_findFirstByAttribute:@"title" withValue:title inContext:self.sharedContext];
                [productCategory MR_deleteEntityInContext:self.sharedContext];
                [self.sharedContext MR_saveToPersistentStoreAndWait];
            }
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,YES,nil);
        } else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,NO, error);
        }
    }];
}
@end
